<?php

namespace app\shop\controller;


use app\common\model\ShopMessageTip;
use app\common\model\ShopStore;
use app\common\service\Status;
use app\shop\model\ShopStoreGoodsSpec;
use buildView\Button;
use buildView\Filter;
use think\Controller;
use buildView\Detail;
use buildView\Form;
use buildView\Grid;
use app\shop\model\ShopOrder;
use think\Db;
use think\facade\View;
use vendor\dayin\HttpClient;
use app\shop\model\ShopOrderRefund;
use app\common\service\LatLngTranslate;

/**
 * 附近订单管理
 * Class NearOrder
 * @package app\admin\controller
 */
class NearOrder extends Controller
{
     /**
     * 附近订单
     * @auth true
     * @menu true
     * @return string
     */
    public function index(){
        $store = session('store');
        //计算地点经纬度范围
        $around = LatLngTranslate::getAround($store['latitude'],$store['longitude'],5000);
        // 取小数点后6位
        $around['minLat'] = sprintf("%.6f",substr(sprintf("%.8f", $around['minLat']), 0, -2));
        $around['maxLat'] = sprintf("%.6f",substr(sprintf("%.8f", $around['maxLat']), 0, -2));
        $around['minLng'] = sprintf("%.6f",substr(sprintf("%.8f", $around['minLng']), 0, -2));
        $around['maxLng'] = sprintf("%.6f",substr(sprintf("%.8f", $around['maxLng']), 0, -2));
        
        $grid = new Grid(new ShopOrder);
        $grid->model()->where('type',1)->where('status',8)->where('latitude','>=',$around['minLat'])->where('latitude','<=',$around['maxLat'])->where('longitude','>=',$around['minLng'])->where('longitude','<=',$around['maxLng']);
        $grid->setTitle('预约列表');
        $grid->setFromOpen();
        $grid->user()->headimg('会员')->display(function ($val, $data, $html) {
            return $html . '<br>' . $data['user']['nickname'];
        })->setExcelData(function($val,$data){
            return $data['user']['nickname'];
        })->image(50);
        // if ($store){
        //     $grid->where('store_id',$store['id']);
        // }else{
        //     $grid->store()->name('门店');
        // }
        $grid->store()->name('距离(附近5km)')->display(function ($val, $data) {
            $store = session('store');
            //  ShopOrder::getDistanceAttr($data['latitude'],$data['longitude']);
            return $distance = LatLngTranslate::GetDistance($data['latitude'],$data['longitude'],$store['latitude'],$store['longitude']) . 'km';
        });
        
        $grid->order_no('订单编号')->setExcelData(function($val,$data){
            return ' '.$data['order_no'];
        })->hide();
        $grid->title('订单标题')->hide();
        $grid->status('订单状态')->using(Status::ORDERSTATUS())->hide();
        $grid->total_price('订单金额')->hide();
        $grid->pay_price('已支付金额')->hide();
        $grid->create_at('下单时间')->hide();
        $grid->pay_time('支付时间')->hide();
        $grid->user_address('地址')->setExcelData(function ($vals,$data){
            return Db::name('user')->where('id',$data['uid'])->find()['user_address'];
        });
        $grid->detailed_address('详细地址')->setExcelData(function ($vals,$data){
            return Db::name('user')->where('id',$data['uid'])->find()['detailed_address'];
        });
        $grid->type('订单类型')->using(Status::SHOPTYPE())->badge();
        $grid->status('订单信息')->display(function ($val, $data, $html) {
            if (is_null($data['pay_time'])) {
                $pay_time = '--';
            } else {
                $pay_time = $data['pay_time'];
            }

            $html = "订单编号：<strong class='color-text'>{$data['order_no']}</strong><br>订单状态：{$html}<br>订单金额：<strong class='color-blue'>{$data['total_price']}</strong>&nbsp;&nbsp;已支付：<strong class='color-blue'>{$data['pay_price']}</strong><br>下单时间：{$data['create_at']}<br>支付时间：{$pay_time}";
            return $html;
        })->align('left')->excelClose()->using(Status::ORDERSTATUS())->badge();
        $grid->goods_record('商品信息')->display(function ($vals, $data) {
            $htmlArr = [];
            foreach ($vals as $val) {
                $htmlArr[] = "<p>{$val['good_title']}</p><p>{$val['spec_name']}</p><p class='color-desc'>售价：{$val['price']} 元 数量：{$val['num']}</p>";
            }
            $html = implode('<hr>', $htmlArr);
            return $html;
        })->minWidth(300)->setExcelData(function ($vals,$data){
            $html = '';
            foreach ($vals as $val) {
                $html .= "{$val['good_title']} {$val['spec_name']} 售价：{$val['price']} 元 数量：{$val['num']} ";
            }
            return $html;
        })->align('left');
        $grid->actions(function ($action, $data) {
            $action->hideEdit();
            $action->hideDel();
            if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                $button = new Button('已支付','normal','sm','layui-icon-rmb');
                $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                $action->append($button);
            }
            // 获取售后表里的数据
            $select = model("ShopOrderRefund")->where('order_id',$data['id'])->find();
            
            $store = session('store');
            if ($data['type'] == 1 && $data['status'] == 8) {
                    $button2 = new Button('接单');
                    $button2->save($data['id'], ['status' => 8,'store_id' => $store['id']], url('begainActivity'), '确认接单？');
                    $action->append($button2);
            }
        });
        $grid->filter(function (Filter $filter)use($store) {
            // if (!$store) {
            //     $data = ShopStore::field('id,name')->column('name','id');
            //     $filter->eq('store_id', '门店')->select($data);
            // }
            $data = ShopStore::field('id,name')->where('id',$store['id'])->column('name','id');
            $filter->eq('store_id', '门店')->select($data);
            $filter->like('user.nickname', '会员');
            $filter->like('user.phone', '手机号');
            $filter->eq('order_no', '订单号');
            $filter->eq('type', '订单类型')->select(Status::SHOPTYPE());
            $filter->eq('status', '订单状态')->select(Status::ORDERSTATUS());
            $filter->eq('pay_type', '支付方式')->select(Status::PAYTYPE());
            $filter->dateBetween('create_at', '下单时间');
        });
        $grid->hideDeletesButton();
        $grid->hideAddButton();
        return $grid->view();
    }
    
    /**
     * 确认接单
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/10/8 17:08
     */
    public function begainActivity()
    {
        $order_id = $this->request->post('id');
        $status = $this->request->post('status');
        $store_id = $this->request->post('store_id');
        $order = ShopOrder::with('store')->where('status', $status)->get($order_id);
        if ($order) {
            switch ($status){
                case 8:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已接单";
                    $order->status = 2;
                    $order->store_id = $store_id;
                    break;
                case 3:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已洗衣结束,请尽快到店领取衣物";
                    $order->status = 4;
                    break;
                case 4:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已领取衣物";
                    $order->status = 5;
                    break;
                default:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已收件洗衣中,请耐心等待";
                    $order->status = 3;
                    break;
            }
            $order->save();
            if ($order['uid']){
                $data = [
                    'uid' => $order['uid'],
                    'title' => '校园快洗',
                    'content' => $content
                ];
                ShopMessageTip::create($data);
            }
            $this->success('成功','');
        } else {
            $this->error('该订单无效或已开始洗衣');
        }
    }
        
    /**
     * 详情
     * @auth true
     * @menu true
     * @return string
     */
    public function detail()
    {
        $detail = new Detail(new ShopOrder);
        $detail->setTitle('订单详情');
        $data = $detail->getModelData();
        $detail->layout('订单信息', 6, function ($detail) {
            $detail->type('订单类型')->using(Status::SHOPTYPE());
            $detail->order_no('订单号');
            $detail->freight_price('快递费');
            $detail->goods_price('商品总价');
            $detail->total_price('订单金额');
            $detail->is_pay('支付状态')->display(function ($val,$data,$html){
                if ($data['pay_type'] == 2 && $data['is_pay'] == 0 && $data['status'] == 1) {
                    $button = new Button('已支付','normal','sm','layui-icon-rmb');
                    $button->href(url('updatePayPrice') . '?id=' . $data['id'], 'modal');
                    $html = $button->render();
                }
                return $html;
            })->using(Status::PAYSTATUS())->badge();
            $detail->pay_type('支付方式')->using(Status::PAYTYPE());
            $detail->pay_no('微信流水号');
            $detail->pay_price('支付金额￥');
            $detail->pay_time('支付时间');
            $detail->status('订单状态')->using(Status::ORDERSTATUS())->badge();
            $detail->create_at('下单时间');
        })->layout('门店信息', 6, function ($detail) {
            $detail->store()->name('门店名称');
            $detail->store()->logo('Logo')->image(50, 50, 50);
            $detail->store()->full_address('地址');
        })->layout('会员信息', 6, function ($detail) {
            $detail->user()->nickname('会员昵称');
            $detail->user()->headimg('会员头像')->image(50, 50, 50);
        });
        $detail->hasManyArray('goods_record', '商品信息', 12, function ($detail) {
            $detail->good_title('商品标题');
            $detail->price('商品售价');
            $detail->num('数量');
        });
        return $detail->view();
    }

    public function remind_num(){
        $count = ShopOrder::where('type',1)->where('express_type',2)->where('status',2)->count();
        $stock_warning = sysconf('stock_warning');
        $stock_num = ShopStoreGoodsSpec::whereRaw('stock < '.$stock_warning)->where('is_deleted',0)->count('DISTINCT gid');
        $this->success('成功','',[
            'order_num'=>$count,
            'stock_num'=>$stock_num,
        ]);
    }
}
